import isHotkey from 'is-hotkey'

export class KeyboardEvent {
    private editor: any;
    private container: HTMLElement;
    private view: any;
    private isComposing: boolean = false;

    constructor(editor: any, container: HTMLElement, view: any) {
        this.editor = editor;
        this.container = container;
        this.view = view
    }


    compositionStartHandler_(e: any) {
        this.isComposing = true
    }

    compositionEndHandler_(e: any) {
        this.isComposing = false
        const text = e.data;
        if (text) {
            this.editor.insertTextAtCursor(text);
        }
    }

    beforeInputHandler_(e: any) {
        const inputType: string = e.inputType;
        if (inputType === 'insertCompositionText' || inputType === 'deleteCompositionText') {
            return
        }
        e.preventDefault()
        switch (inputType) {
            case 'insertText':
                const text = e.data
                if (text) {
                    this.editor.insertTextAtCursor(text);
                }
                break
            case 'deleteContentForward':
            case 'deleteContentBackward':
                this.editor.deleteTextAtCursor()
                break
            case 'insertParagraph':
                this.editor.insertTextAtCursor('\n');
                break
            //粘贴
            case 'insertFromPaste':
                navigator.clipboard
                    .readText()
                    .then((v) => {
                        this.editor.insertTextAtCursor(v);

                    })
                    .catch((v) => {
                        console.log("获取剪贴板失败: ", v);
                    });
                break

        }
    }

    selectionchangeHandler_(selection: { anchor: any; focus: any; }) {
        if (selection && !this.isComposing) {
            console.log('selection change')
            this.editor.setSelection(selection.anchor, selection.focus)
        }
    }

    keydownHandler_(e: any) {
        if (isHotkey('Control+z', e)) {
            e.preventDefault()
            this.editor.undo && this.editor.undo()
        } else if (isHotkey('Control+Shift+z', e)) {
            e.preventDefault()
            this.editor.redo && this.editor.redo()
        }
    }

    addListeners() {
        this.container.addEventListener('beforeinput', this.beforeInputHandler_.bind(this))
        this.container.addEventListener('keydown', this.keydownHandler_.bind(this))
        this.container.addEventListener('compositionstart', this.compositionStartHandler_.bind(this))
        this.container.addEventListener('compositionend', this.compositionEndHandler_.bind(this))
        this.view.on('selection-change', this.selectionchangeHandler_.bind(this))
    }
}